package edu.lingnan.constroller;

import edu.lingnan.common.Result;
import edu.lingnan.pojo.Product;
import edu.lingnan.pojo.ShoppingCart;
import edu.lingnan.service.ProductService;
import edu.lingnan.service.ShoppingCartService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author xBaozi
 * @version 1.0
 * @classname ShoppingCartController
 * @description 购物车控制器
 * @date 2022/5/27 18:39
 */
@RestController
@RequestMapping("/shopping-cart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private ProductService productService;

    //加入购物车
    @RequestMapping("/addShoppingCart")
    public Result addShoppingCart(ShoppingCart shoppingCart) {
        String str= shoppingCartService.addShoppingCart(shoppingCart);

        Result result = new Result();
        result.setCode(Result.SUCCESS_CODE);
        result.setData(shoppingCart);
        result.setMsg(str);
        return result;
    }

    //查看购物车
    @RequestMapping("/myShoppingCart/{userId}")
    public Result myShoppingCart(@PathVariable("userId") Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartService.myShoppingCart(userId);
        List<Product> productList=new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            Long productId = shoppingCart.getProductId();
            List<Product> productList1 = productService.selectProductById(productId);
            productList.addAll(productList1);
        }
        List<Object> objectList = new ArrayList<>();
        objectList.add(productList);
        objectList.add(shoppingCartList);

        Result result = new Result();
        result.setCode(Result.SUCCESS_CODE);
        result.setData(objectList);
        if (shoppingCartList.isEmpty()) {
            result.setMsg("购物车空空如也，快去逛逛吧");
        } else {
            result.setMsg("购物车已加载");
        }
        return result;
    }

    //购物车删除商品
    @RequestMapping("/deleteMyProduct")
    public Result deleteMyProduct(ShoppingCart shoppingCart) {

        String msg = shoppingCartService.deleteMyProduct(shoppingCart);
        Result result = new Result();
        result.setCode(Result.SUCCESS_CODE);
        result.setData(shoppingCart);
        result.setMsg(msg);
        return result;
    }

}
